import React, { useState, useCallback, useRef } from 'react';
import { Input, Button, Spin, List, message, type GetProp, Typography } from 'antd';
import { useXAgent, useXChat, Bubble, Sender } from '@ant-design/x';
import type { BubbleProps } from '@ant-design/x';
import { UserOutlined } from '@ant-design/icons';
import markdownit from 'markdown-it';
import Apis from '@/Apis';

import styles from './index.module.css';

const ChatApp: React.FC = () => {
    const [question, setQuestion] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const [requestType, setRequestType] = useState<'normal' | 'rag' | 'tools'>('normal');
    const [history, setHistory] = useState<
        Array<{ role: string; content: string }>
    >([]);

    const requestFn = useRef(Apis.DeepseekApis['question']);
    const md = markdownit({ html: true, breaks: true });

    let fullContent = '';

    const roles: GetProp<typeof Bubble.List, 'roles'> = {
        ai: {
            placement: 'start',
            avatar: { icon: <UserOutlined />, style: { background: '#fde3cf' } },
            typing: { step: 5, interval: 20 },
            style: {
                maxWidth: 600,
            },
            variant: "shadow",
            messageRender: (content: string) => {
                const thinkMatch = content.match(/<think>([\s\S]*?)<\/think>/);
                const thinkContent = thinkMatch ? thinkMatch[1].trim() : '';

                // 匹配正文部分（<think> 标签之外的内容）
                const answerMatch = content.replace(/<think>[\s\S]*?<\/think>/, '').trim();
                const answerContent = answerMatch;
                return (
                    <div
                        className={styles.aiMessage}
                        style={{
                            textAlign: 'left',
                        }}
                    >
                        {thinkContent && (
                            <div className={styles.thinkContent} dangerouslySetInnerHTML={{ __html: md.render(thinkContent) }} />
                        )}
                        <Typography>
                            {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
                            <div className={styles.answerContent} dangerouslySetInnerHTML={{ __html: md.render(answerContent) }} />
                        </Typography>
                    </div>
                );
            }
        },
        local: {
            variant: "shadow",
            placement: 'end',
            avatar: { icon: <UserOutlined />, style: { background: '#87d068' } },
        },
    };

    // 使用 useXAgent 和 useXChat 来管理对话流
    const [agent] = useXAgent({
        request: async ({ message: question }, { onUpdate, onSuccess, onError }) => {
            setLoading(true);
            try {
                const handleSuccess = () => {
                    setLoading(false);
                    onSuccess(fullContent);
                    fullContent = '';
                };
                const handleUpdate = (answer: string) => {
                    fullContent += answer;
                    onUpdate(fullContent);
                };
                Apis.DeepseekApis.eventSource({ onSuccess: handleSuccess, onUpdate: handleUpdate, onError, });
                // 发送问题到/deepseek/question接口
                requestFn.current(question!);
            } catch (error) {
                message.error('Failed to fetch answer');
                setLoading(false);
            }
        },
    });

    const { onRequest, messages } = useXChat({
        agent, defaultMessages: [
            {
                id: 'init',
                message: '你好，我是智能问答机器人，请问有什么可以帮助你的吗？',
                status: 'success',
            },
        ],
    });

    // 处理发送消息
    const handleSend = () => {
        if (!question.trim()) return;

        const newHistory = [...history, { role: 'user', content: question }];

        setHistory(newHistory);

        onRequest(question);

        setQuestion('');
    };

    const handleAddRagData = async () => {
        await Apis.DeepseekApis.addRagData('src/assets/data/中华人民共和国民法典.pdf');
    }

    const handleChangeRAG = () => {
        const isRag = requestType === 'rag';
        setRequestType(isRag ? 'normal' : 'rag');
        requestFn.current = Apis.DeepseekApis[isRag ? 'question' :'rag'];
    }
    
    const handleChangeTools = () => {
        const isTools = requestType === 'tools';
        setRequestType(isTools ? 'normal' : 'tools');
        requestFn.current = Apis.DeepseekApis[isTools ? 'question' :'tools'];
    }


    // 处理输入框变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setQuestion(e.target.value);
    };

    return (
        <div className={styles.content}>
            <h1>智能问答</h1>
            <div className={styles.chatWrapper}>
                <div className={styles.chatContainer}>
                    <Bubble.List
                        className={styles.chatList}
                        roles={roles}
                        items={messages.map((msg, index) => ({
                            key: index,
                            content: msg.message,
                            // loading: msg.status === 'loading',
                            role: msg.status === 'local' ? 'local' : 'ai'
                        }))}
                    />

                    <div>
                        <Input
                            placeholder="请输入问题..."
                            value={question}
                            onChange={handleInputChange}
                            onPressEnter={handleSend}
                            style={{ width: '70%', marginRight: '10px' }}
                        />
                        <Button type="primary" onClick={handleSend} loading={loading}>
                            发送
                        </Button>
                    </div>
                </div>
                <div className={styles.sideBar}>

                    <Button type="primary" onClick={handleAddRagData} loading={loading}>
                        添加知识库
                    </Button>

                    <Button type="primary" onClick={handleChangeRAG} loading={loading}>
                        { requestType === 'rag' ? '关闭RAG' : '开启RAG' }
                    </Button>
                    <Button type="primary" onClick={handleChangeTools} loading={loading}>
                        { requestType === 'tools' ? '关闭Tools' : '开启Tools' }
                    </Button>

                </div>
            </div>


        </div>
    );
};

export default ChatApp;